package com.wetao.module_demo_cyh;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tstudy.blepenlib.BlePenStreamManager;
import com.tstudy.blepenlib.data.CoordinateInfo;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.bean.response.StudentInfo;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.net.RetryWithDelay;
import com.wetao.lib_common.net.RxUtils;
import com.wetao.lib_common.net.ServerUtils;
import com.wetao.lib_common.net.callback.RequestCallback;
import com.wetao.lib_common.net.callback.RxErrorHandler;
import com.wetao.lib_common.net.cookies.PersistentCookieStore;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.MultiClickUtil;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.utils.oss.OssParams;
import com.wetao.lib_common.utils.oss.UploadOss;
import com.wetao.lib_common.view.Dialogue_title;
import com.wetao.lib_common.view.kyloading.KyLoadingBuilder;
import com.wetao.module_demo_cyh.blepen.MyProgress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

import static com.tstudy.blepenlib.constant.Constant.PEN_COODINAT_MESSAGE;
import static com.tstudy.blepenlib.constant.Constant.PEN_DOWN_MESSAGE;
import static com.tstudy.blepenlib.constant.Constant.PEN_UP_MESSAGE;


public class YundiePenTestDrawActivity extends BaseActivity<EmptyCon.View, EmptyPre>
        implements EmptyCon.View{
    private static final String TAG = "YundiePenTestDrawActivity_tag";
    private static final String DOT_DOWN = "down";
    private static final String DOT_MOVE = "move";
    private static final String DOT_UP = "UP";
    private static final float DOT_PW = 5600;
    private static final float DOT_PH = 7920;
    private static final float PIC_W = 1004;
    private static final float PIC_H = 1404;
    private CoordinateInfo mCoordinateInfo;

    private String mPenMac;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS", Locale.CHINA);
    private TextView txt_coordinate;
    private TextView txt_force;
    private TextView txt_paper_addres;
    private TextView txt_write;
    private String writeString;
    private Context mContext;
    private ProgressDialog progressDialog;
    private MyProgress myProgress;
    private TextView txt_progress;
    private TextView txt_time;


    FrameLayout fl_doodle;
    String picFilePath;
    private Bitmap doodle_bitmap;

    private Dialogue_title titleDialog;
    private Dialogue_title backDialog;
    private KyLoadingBuilder kyLoadingBuilder;

    private float temp_x = 0;
    private float temp_y = 0;
    private String writeString_prev;

    @Override
    public int getLayoutId() {
        return R.layout.activity_yundie_pen_test_draw;
    }

    @Override
    public EmptyPre createPresenter() {
        return new EmptyPre(this);
    }

    @Override
    public EmptyCon.View createView() {
        return this;
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }

    @Override
    public void init() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventBus.getDefault().register(this);
        mContext = YundiePenTestDrawActivity.this;
        Intent intent = getIntent();
        mPenMac = intent.getStringExtra("penMac");
        if(mPenMac == null) {
            finish();
            return;
        }
        picFilePath = getPicFilePath(this, mPenMac.replaceAll(":", "_"));
        //doodle_bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yundie_pic);
        //LogUtils.i("图片宽高：" + doodle_bitmap.getWidth() + ", " + doodle_bitmap.getHeight());
        initView();
    }

    //
    public static String getPicFilePath(Context mContext, String name) {
        //String dirPath = mContext.getExternalFilesDir(null).getAbsolutePath();
        String dirPath = Constants.FILE_PATH;
        dirPath = dirPath + File.separator + "tsdpen";
        File picDirF = new File(dirPath);
        if (!picDirF.exists()) {
            boolean mkdirs = picDirF.mkdirs();
            if (!mkdirs) {
                LogUtils.e("m1:创建失败picDir：" + dirPath);
            } else {
                LogUtils.i("m1:创建成功picDir");
            }
        }
        String filePath = dirPath + File.separator + name + ".png";
        LogUtils.i("m1: 图片存储的路径：" + filePath);
        return filePath;
    }

    private void initView() {

        kyLoadingBuilder = new KyLoadingBuilder(this);

        fl_doodle = findViewById(R.id.fl_doodle);

        txt_time = findViewById(R.id.txt_time);
        myProgress = findViewById(R.id.pgsBar);
        txt_progress = findViewById(R.id.txt_progress);
        txt_write = findViewById(R.id.txt_write);
        txt_paper_addres = findViewById(R.id.txt_paper_addres);
        txt_force = findViewById(R.id.txt_force);
        txt_coordinate = findViewById(R.id.txt_coordinate);

        downLoadImg();
    }

    private void downLoadImg() {
        Glide.with(this).asBitmap().load(R.drawable.yundie_pic)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        Thread thread1 = getMainLooper().getThread();
                        Thread thread2 = Thread.currentThread();

                        LogUtils.i("-----doodle----glide主线程名字: "+thread1.getName() );
                        LogUtils.i("-----doodle----glide当前线程名字: "+thread2.getName() );

                        LogUtils.i("Glde图片-成功");
                        doodle_bitmap = resource;
                        LogUtils.i("图片宽高：" + doodle_bitmap.getWidth() + ", " + doodle_bitmap.getHeight());
                        initDoodleData_pre();
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        LogUtils.e("Glde图片-失败 url = " + picFilePath);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    private void initDoodleData_pre() {
        //initDoodleData();

        Observable.timer(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:initDoodleData_pre===onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                        BlePenStreamManager.getInstance().setRealtimeMode();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //w=1004,5600; h=1404, 7920
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(CoordinateInfo coordinateInfo) {
        //其中笔的状态为move时坐标携带的点阵地址、坐标、压力、笔画数、时间戳有效。down、up时坐标信息无效
        //mStrokeView.addDot(coordinateInfo);
        //其中笔的状态为move时坐标携带的坐标信息（点阵地址、坐标、压力）有效，
        // down、up时坐标信息（点阵地址、坐标、压力）无效，绘制一般只取落笔抬笔事件用于重置绘制状态
        String writeString_prev = writeString;
        switch (coordinateInfo.state) {
            case PEN_DOWN_MESSAGE:
                writeString = DOT_DOWN;
                break;
            case PEN_COODINAT_MESSAGE:
                writeString = DOT_MOVE;
                break;
            case PEN_UP_MESSAGE:
                writeString = DOT_UP;
                break;
            default:
                writeString = DOT_UP;
        }

        LogUtils.i("onCoordDraw: x=" + coordinateInfo.coordX + "  y=" + coordinateInfo.coordY + "  force=" + coordinateInfo.coordForce +
                "  pageAddress=" + coordinateInfo.pageAddress + "  time=" + coordinateInfo.timeLong + "  stroke=" + coordinateInfo.strokeNum + "  state=" + writeString + ", isOFFLine=" + coordinateInfo.isOFFLine);

        txt_time.setText("time:" + simpleDateFormat.format(new Date(coordinateInfo.timeLong)));
        txt_write.setText(writeString);
        txt_coordinate.setText(coordinateInfo.coordX + "/" + coordinateInfo.coordY);
        txt_force.setText(coordinateInfo.coordForce + "");
        txt_paper_addres.setText(coordinateInfo.pageAddress);
        if (coordinateInfo.isOFFLine) {
            if (myProgress.getVisibility() == View.GONE) {
                LogUtils.i("run:离线传输开始 ");
                myProgress.setVisibility(View.VISIBLE);
                txt_progress.setVisibility(View.VISIBLE);
            }
            if (coordinateInfo.offLineDataAllSize != 0) {
                myProgress.setProgress(100 * coordinateInfo.offLineDateCurrentSize / coordinateInfo.offLineDataAllSize);
                txt_progress.setText(" 上传进度：" + coordinateInfo.offLineDateCurrentSize + "/" + coordinateInfo.offLineDataAllSize);
            }
            if (coordinateInfo.offLineDateCurrentSize == coordinateInfo.offLineDataAllSize && myProgress.getVisibility() == View.VISIBLE) {
                myProgress.setVisibility(View.GONE);
                LogUtils.i("run:离线传输完毕 ");
            }
        }
        temp_x = 0;
        temp_y = 0;
        if(DOT_DOWN.equals(writeString_prev) && DOT_MOVE.equals(writeString)) {
            //按下
            temp_x = getRealX(coordinateInfo.coordX);
            temp_y = getRealY(coordinateInfo.coordY);
            //mTouchGestureListener.r_onDown(temp_x, temp_y);
            //mTouchGestureListener.r_onScrollBegin(temp_x, temp_y);
        } else if(DOT_MOVE.equals(writeString_prev) && DOT_MOVE.equals(writeString)) {
            //移动
            temp_x = getRealX(coordinateInfo.coordX);
            temp_y = getRealY(coordinateInfo.coordY);
            //mTouchGestureListener.r_onScroll(temp_x, temp_y);
        } else if(DOT_MOVE.equals(writeString_prev) && DOT_UP.equals(writeString)) {
            //弹起
            temp_x = getRealX(mCoordinateInfo.coordX);
            temp_y = getRealY(mCoordinateInfo.coordY);
            //mTouchGestureListener.r_onScrollEnd(mCoordinateInfo.coordX, mCoordinateInfo.coordY);
        }
        mCoordinateInfo = coordinateInfo;

    }

    private float getRealX(float x) {
        x = x >= DOT_PW ? DOT_PW : x;
        return x * PIC_W / DOT_PW;
    }
    private float getRealY(float y) {
        y = y >= DOT_PH ? DOT_PH : y;
        return y * PIC_H / DOT_PH;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (progressDialog != null) {
            progressDialog = new ProgressDialog(mContext);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventBus.getDefault().unregister(this);
        kyLoadingBuilder.dismiss();
    }


    private void savePic(Bitmap bitmap) {

        FileUtils.saveBitmap(bitmap, picFilePath);

        final String uploadFileName = "tsdtest/" + mPenMac.replaceAll(":", "_") + ".png";

        UploadOss.getInstance().upload2OSS(uploadFileName, picFilePath, ossUploadListener, null);

        //getStudentInfoReq(ComUtil.getHashmapByStr(new String[]{"imei"},new String[]{"867400020316612"}));
    }

    //http://newpage-dev.oss-cn-hangzhou.aliyuncs.com/tsdtest/A8_90_42_0E_AC_EB.png
    UploadOss.OnUploadListener ossUploadListener = new UploadOss.OnUploadListener() {
        @Override
        public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {
            Thread thread1 = getMainLooper().getThread();
            Thread thread2 = Thread.currentThread();
            LogUtils.i("-----doodle----OSSUploadListener主线程名字: "+thread1.getName() );
            LogUtils.i("-----doodle----OSSUploadListener当前线程名字: "+thread2.getName() );
            LogUtils.i("oss路径：" + uploadFile);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.initToast("上传图片成功");
                    kyLoadingBuilder.dismiss();
                    finish();
                }
            });

            return null;
        }

        @Override
        public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.initToast("上传图片失败");
                    kyLoadingBuilder.dismiss();
                }
            });

            return null;
        }
    };

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        LogUtils.i("m1:--onKeyDown keyCode = " + keyCode);
        switch (keyCode) {

            case KeyEvent.KEYCODE_DPAD_CENTER:{
                if(!MultiClickUtil.isFastClick()) {
                    ToastUtil.initToast("不允许连续点击");
                    return true;
                }
                dialogue_center();

            }break;
            case KeyEvent.KEYCODE_F11:
            case KeyEvent.KEYCODE_BACK:{
                /*if(!MultiClickUtil.isFastClick()) {
                    ToastUtil.initToast("不允许连续点击");
                    return true;
                }*/

                dialogue_back();

            }break;

        }
        return super.onKeyUp(keyCode, event);
    }

    public void dialogue_center() {

        if(titleDialog == null) {
            titleDialog = new Dialogue_title(this, R.style.MyDialog);
            titleDialog.setYesOnclickListener(getResources().getString(R.string.btn_ok), new Dialogue_title.onYesOnclickListener() {
                @Override
                public void onYesOnclick() {
                    if (titleDialog.isShowing()) {
                        titleDialog.dismiss();
                    }
                    LogUtils.i("m1: onYesOnclick");
                    clickSubmit();
                }
            });
            titleDialog.setNoOnclickListener(getResources().getString(R.string.btn_no), new Dialogue_title.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    if (titleDialog.isShowing()) {
                        titleDialog.dismiss();
                    }
                    LogUtils.i("m1: onNoClick");
                }
            });

            titleDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    //hideBar();
                }
            });

            titleDialog.setCancelable(false);

            titleDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                    final int action = event.getAction();

                    System.out.println("action=" + event.getAction());
                    System.out.println("####" + keyCode);

                    // 屏蔽连续按下事件,只监听up事件
                    if (action != KeyEvent.ACTION_UP) {
                        System.out.println("屏蔽");
                        return true;
                    } else {
                        switch (keyCode) {
                            case KeyEvent.KEYCODE_DPAD_CENTER:
                                if(!MultiClickUtil.isFastClick()) {
                                    break;
                                }
                                LogUtils.i("m1: dialog: KEYCODE_DPAD_CENTER");
                                if (titleDialog != null) {
                                    titleDialog.yesclick();
                                }
                                break;
                            case KeyEvent.KEYCODE_BACK:
                                if(!MultiClickUtil.isFastClick()) {
                                    break;
                                }
                                LogUtils.i("m1: dialog: KEYCODE_BACK");
                                if (titleDialog != null) {
                                    titleDialog.noclick();

                                }
                                break;
                        }
                    }
                    return true;
                }

            });
        }
        String str_all = "确定提交吗？";
        MultiClickUtil.clearLastClickTime();
        titleDialog.setMessage(str_all);
        titleDialog.show();

    }

    private void clickSubmit() {
        kyLoadingBuilder.setText("正在提交，请稍后...");
        kyLoadingBuilder.show();
        //mDoodle.save();
    }

    public void dialogue_back() {
        if(backDialog == null) {
            backDialog = new Dialogue_title(this, R.style.MyDialog);
            String str_all = "是否确认退出？";

            backDialog.setMessage(str_all);
            backDialog.setYesOnclickListener(getResources().getString(R.string.btn_ok), new Dialogue_title.onYesOnclickListener() {
                @Override
                public void onYesOnclick() {
                    if (backDialog.isShowing()) {
                        backDialog.dismiss();
                    }
                    LogUtils.i("m1: onYesOnclick");
                    finish();
                    //mDoodle.save();
                }
            });
            backDialog.setNoOnclickListener(getResources().getString(R.string.btn_no), new Dialogue_title.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    if (backDialog.isShowing()) {
                        backDialog.dismiss();
                    }
                    LogUtils.i("m1: onNoClick");
                }
            });

            backDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    //hideBar();
                }
            });

            backDialog.setCancelable(false);


            backDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                    final int action = event.getAction();

                    System.out.println("action=" + event.getAction());
                    System.out.println("####" + keyCode);

                    // 屏蔽连续按下事件,只监听up事件
                    if (action != KeyEvent.ACTION_UP) {
                        System.out.println("屏蔽");
                        return true;
                    } else {
                        switch (keyCode) {
                            case KeyEvent.KEYCODE_DPAD_CENTER:
                                if(!MultiClickUtil.isFastClick()) {
                                    break;
                                }
                                LogUtils.i("m1: dialog: KEYCODE_DPAD_CENTER");
                                if (backDialog != null) {
                                    backDialog.yesclick();
                                }
                                break;
                            case KeyEvent.KEYCODE_BACK:
                                if(!MultiClickUtil.isFastClick()) {
                                    break;
                                }
                                LogUtils.i("m1: dialog: KEYCODE_BACK");
                                if (backDialog != null) {
                                    backDialog.noclick();

                                }
                                break;
                        }
                    }
                    return true;
                }

            });
        }

        MultiClickUtil.clearLastClickTime();
        backDialog.show();
    }

    //getStudentInfoReq(ComUtil.getHashmapByStr(new String[]{"imei"},new String[]{imei}));
    private void getStudentInfoReq(HashMap<String, String> map){
        String json =(JsonUtils.getmGson()).toJson(map);
        RequestBody requestBody =  RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),json);
        ServerUtils.getCommonApi().getStudentPenBoxInfo(requestBody)
                .retryWhen(new RetryWithDelay(3,2))
                .compose(RxUtils.<StudentInfo>getSchedulerTransformer())
                .subscribe(new RequestCallback<StudentInfo>(this, RxErrorHandler.getInstance(),false,false) {
                    @Override
                    public void onNext(StudentInfo studentInfo) {
                        checkStudentInfo(studentInfo);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        checkStudentInfo(null);
                    }
                });
    }

    /**
     * 检验返回信息
     * @param studentInfo
     */
    private void checkStudentInfo(StudentInfo studentInfo) {
        if (studentInfo!=null && studentInfo.getData()!=null){
            LogUtils.i("studentInfo ==" + (JsonUtils.getmGson()).toJson(studentInfo));
            if (studentInfo.getData().getName()!=null && studentInfo.getData().getStudentId()!=null){
                PersistentCookieStore.getCookieStore().saveUserInfo(studentInfo.getData().getName(),
                        studentInfo.getData().getStudentId());
                SPUtils.getInstance().put(Constants.HEAD_XTOKEN,studentInfo.getData().getToken());

                final String uploadFileName = "tsdtest/" + mPenMac.replaceAll(":", "_") + ".png";

                UploadOss.getInstance().upload2OSS(uploadFileName, picFilePath, ossUploadListener, null);
            }else {
                //initView();
                ToastUtil.initToast("测试登录失败null");
            }
        }else {
            //initView();
            ToastUtil.initToast("测试登录失败err");
        }
    }

}
